<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/30
 * Time: 17:16
 */

namespace App\Model\Backstage;


use App\Model\Base;
use Illuminate\Support\Facades\DB;
use App\Model\Account\SystemType;

class CustomersFollow extends Base
{
    public $customersfollow;
    public $customersource;
    public $customers;
    public function __construct()
    {
        parent::__construct();
//        $this->customersfollow = 'customer_follow';
        $this->customersfollow = 'customer_follow_'.$this->branch_id;


//        $this->customersource = 'customer_follow_source';
        $this->customersource = 'customer_follow_source_'.$this->branch_id;


//        $this->customers = 'customers';
        $this->customers = 'customers_'.$this->branch_id;
    }

    /**
     * @param $cid 客源ID
     * @param $cf_fllow_type  跟进方式
     * @param $cf_content  跟进内容
     * @param $cf_room_id  跟进同时 同步的房源ID
     * @return mixed
     */
    public function addCustomersFollow($params)
    {
        if (isset($params['cfs_remind_time']) && $params['cfs_remind_time'] != '') {
            $params['cfs_remind_time'] = strtotime($params['cfs_remind_time']);
        }
        $cf_fllow_Id =  DB::table($this->customersfollow)
            ->insertGetId([
                'cf_c_id' =>$params['cf_c_id'],
                'cf_fllow_type' =>$params['cf_fllow_type'],
                'cf_room_id' =>$params['cf_room_id'],
                'cf_content' =>$params['cf_content'],
                'cf_user_id' =>$params['cf_user_id'],
                'cf_department_id' =>$params['cf_department_id'],
                'cfs_reminder_range' =>$params['cfs_user_id'],//提醒范围
                'cfs_remind_time' => $params['cfs_remind_time'],
                'cfs_content' =>$params['cfs_content'],
                'cf_created_at'=>time()
            ]);
        //更新客源跟进时间
        DB::table($this->customers)->where('c_id',$params['cf_c_id'])->update(['c_followup_time'=>time()]);

        if ($cf_fllow_Id) {
            return $cf_fllow_Id;
        } else {
            return false;
        }
    }

    //房源看房添加客源跟进
    public function roomaddCustomersFollow($params)
    {
        if (isset($params['cfs_remind_time']) && $params['cfs_remind_time'] != '') {
            $params['cfs_remind_time'] = strtotime($params['cfs_remind_time']);
        }
        $cf_fllow_Id =  DB::table($this->customersfollow)
            ->insertGetId([
                'cf_c_id' =>$params['f_customers_id'],//f_customers_id
                'cf_fllow_type' =>$params['f_follow_up_way'],
                'cf_room_id' =>$params['f_room_id'],
                'cf_content' =>$params['f_content'],
                'cf_user_id' =>$params['f_user_id'],
                'cf_department_id' =>$params['f_department_id'],
                'cfs_reminder_range' =>$params['cfs_user_id'],//提醒范围
                'cfs_remind_time' => $params['cfs_remind_time'],
                'cfs_content' =>$params['cfs_content'],
                'cf_created_at'=>time()

            ]);
        //更新客源跟进时间
        DB::table($this->customers)->where('c_id',$params['f_customers_id'])->update(['c_followup_time'=>time()]);

        if ($cf_fllow_Id) {
            return $cf_fllow_Id;
        } else {
            return false;
        }
    }
    /**
     * 修改客源跟进
     */
    public function updateCustomersFollow($params){
        DB::beginTransaction();//开启事务
        $cusData = DB::table($this->customersfollow)->where('cf_id',$params['cf_id'])->select('cf_c_id', 'cfs_reminder_range')->first();
        if ($params['cfs_remind_time'] == "") {
            $params['cfs_user_id'] = 0;
            $params['cfs_content'] = '';
            $del = true;
            $cfs_id = true;
        } else{
            $del = true;
            if (intval($cusData->cfs_reminder_range) != 0 && intval($cusData->cfs_reminder_range) != intval($params['cfs_user_id'])) {
                //删除之前的跟进提醒
                $del = DB::table($this->customersource)->where('cf_id',$params['cf_id'])->delete();
            }
            $params['cf_c_id'] = $cusData->cf_c_id;
            $params['cfs_type'] = 2;
            $customerfollowsourde =  new CustomerFollowSourde();
            $cfs_id =  $customerfollowsourde->addCustomerFollowSourde($params,$params['cf_id']);

        }
        //修改客源跟进
        $updateFollow = DB::table($this->customersfollow)
            ->where('cf_id',$params['cf_id'])
            ->update([
                'cf_fllow_type'         => $params['cf_fllow_type'],
                'cf_room_id'            => $params['cf_room_id'],
                'cf_content'            => $params['cf_content'],
                'cf_user_id'            =>  $params['cf_user_id'],
                'cf_department_id'      => $params['cf_department_id'],
                'cfs_remind_time'       => strtotime($params['cfs_remind_time']),
                'cfs_content'           => $params['cfs_content'],
                'cfs_manager_review'    => $params['cfs_manager_review'],
                'cfs_reminder_range'    => $params['cfs_user_id'],
                'cf_update_at'          =>time()
            ]);


        //更新客源跟进时间
        $upCustomerTime = DB::table($this->customers)->where('c_id', $cusData->cf_c_id)->update(['c_followup_time'=>time()]);

        if($del && $cfs_id && $upCustomerTime && $updateFollow){
            DB::commit();
            return true;
        }
        DB::rollback();//失败回滚
        return false;

    }

    /**
     * @param array $map
     * @param $pageLimit
     * @return mixed
     * 获取用户客源跟进数量排行
     * author:lxy
     */
    public function getCustomersFollowNum($map = [], $where = [])
    {
        $user_list = DB::table('user')
            ->leftJoin('department', 'u_d_id', '=', 'id')
            ->where('u_b_id', $this->branch_id)
            ->where($where)
            ->where('u_status', 1)
            ->where('user.is_del', 0)
            ->select(['u_id','u_username','name'])
            ->get()
            ->toArray();
        foreach($user_list as $k => $v){
            $num = DB::table($this->customersfollow)->where($map)->where('cf_user_id', $v->u_id)->count();
            $v->num = $num;
        }
        $list = json_encode($user_list);
        $list = json_decode($list,true);
        array_multisort(array_column($list,'num'),SORT_DESC,$list);
        return $list;

    }

    /*
     * 删除客源跟进
     * Wu Ning
     */

    public function delFollow($param)
    {
        DB::table($this->customersource)->where('cf_id', $param)->delete();

        return DB::table($this->customersfollow)->where('cf_id', $param)->delete();
    }

    /**
     * @param $roomInfoModel
     * @param $params
     * @return mixed
     * 移动员工客源跟进
     */
    public function moves($customersModel, $params){
        $cus_ids = $customersModel->moves($params, 2);
        return DB::table($this->customersfollow)
            ->whereIn('cf_c_id',$cus_ids )
            ->update([
                'cf_user_id'  => $params['to_uid'],
                'cf_update_at'=> time()
            ]);
    }

    /**
     * 客源跟进列表
     * 客源Id 跟进Id 跟进时间 跟进方式 跟进人 跟进人部门 跟进内容 客源编号 客户姓名 交易类型 用途 状态
     * 提醒日期 提醒内容 被提醒人 经理点评
     */
    public function customersFollowLists($pageLimit, $where = [], $keywords){
        if($keywords == ''){
            $list =   DB::table($this->customersfollow)
                ->leftJoin($this->customers, 'c_id', '=', 'cf_c_id')
                //->leftJoin($this->customersource, 'cfs_type_id', '=', 'c_id')
                ->leftJoin('user','cf_user_id','u_id')
                ->leftJoin('department','cf_department_id','id')
                ->where($where)
                ->select($this->customers.'.c_id',$this->customersfollow.'.cf_id',DB::raw('from_unixtime(cf_created_at) as cf_created_at'),'cf_fllow_type','u_username','name',
                    'cf_content','c_numbering','c_user_name','c_trading_type','c_use_type','c_buy_status','cf_user_id','cf_department_id','cfs_remind_time', 'cfs_content','cfs_reminder_range')
                ->orderBy($this->customersfollow.'.cf_id', 'desc')
                ->paginate($pageLimit);
        }else{
            // //跟进的内容    客源的编号  客户姓名   客户电话
            $list =   DB::table($this->customersfollow)
                ->leftJoin($this->customers, 'c_id', '=', 'cf_c_id')
                ->leftJoin('user','cf_user_id','u_id')
                ->leftJoin('department','cf_department_id','id')
                //->leftJoin($this->customersource, 'cfs_type_id', '=', 'c_id')
                ->where(function ($query) use($where, $keywords){
                    $query->where($where)->where('cf_content', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords) {
                    $query->where($where)->where('c_numbering', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('c_user_name', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('c_user_phone', 'like', '%'.$keywords.'%');
                })
                ->select($this->customers.'.c_id',$this->customersfollow.'.cf_id',DB::raw('from_unixtime(cf_created_at) as cf_created_at'),'cf_fllow_type','u_username','name',
                    'cf_content','c_numbering','c_user_name','c_trading_type','c_use_type','c_buy_status','cf_user_id','cf_department_id','cfs_remind_time', 'cfs_content','cfs_reminder_range')
                ->orderBy($this->customersfollow.'.cf_id', 'desc')
                ->paginate($pageLimit);
        }
        if (sizeof($list) == 0) {
            return false;
        }
        foreach($list as $k=>$v){
            if($v->cfs_remind_time != 0){
                $v->cfs_remind_time = date("Y-m-d",$v->cfs_remind_time);
            }else{
                $v->cfs_remind_time = '';
            }
            if($v->cfs_reminder_range != 0){
                $v->cfs_name = $v->cfs_reminder_range == 1 ? '本人' : '本部';
            }else{
                $v->cfs_name = '';
            }

            $v->c_trading_type = SystemType::getTypeDetail($v->c_trading_type);//交易类型
            $v->c_buy_status = SystemType::getTypeDetail($v->c_buy_status); //用途
            $v->c_use_type = SystemType::getTypeDetail($v->c_use_type); //状态
        }
        // dd($list);
        return $list;
    }


    /**
     * 根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
     */
    public function getFollowDay($cid, $uid)
    {
        //根据最后的跟进时间计算出 那天的结束时间
        $cf_created_at = DB::table($this->customersfollow)->where('cf_c_id', $cid)->where('cf_user_id', $uid)->orderBy('cf_id', 'desc')->value('cf_created_at');
        $cfTime = intval(strtotime(date('Y-m-d', $cf_created_at).' 23:59:59'));
        //当天的结束时间
        $nowTime = intval(strtotime(date('Y-m-d', time()).' 23:59:59'));
        //最后跟进的天  不是今天的话
        if ($cfTime != $nowTime) {
            return 2;
        }
        return 1;
    }









}